package lol.clann.minecraft.springboot.plugin.bukkit.impl;

import lol.clann.minecraft.springboot.api.bukkit.utils.MaterialUtils;
import lol.clann.minecraft.springboot.api.model.reflect.FieldInvoker;
import relocate.com.google.common.collect.BiMap;
import relocate.com.google.common.collect.HashBiMap;
import org.bukkit.Material;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 *
 * @author pyz
 * @date 2019/7/11 1:47 AM
 */
@Service
public class MaterialUtilsImpl implements MaterialUtils {

    private static FieldInvoker id;
    private static BiMap<Integer, Material> byId = HashBiMap.create();
    private static Map<String, Material> byName = new HashMap<>();

    static {
        try {
            id = new FieldInvoker(Material.class.getDeclaredField("id"));
        } catch (NoSuchFieldException e) {
            throw new RuntimeException(e);
        }
        for (Material material : Material.values()) {
            byName.put(material.name(), material);
            byId.put((Integer) id.get(material), material);
        }
    }

    @Override
    public int getId(Material material) {
        return byId.inverse().get(material);
    }

    @Override
    public Material getById(int id) {
        return byId.get(id);
    }

    @Override
    public Material getById(String id) {
        return byName.get(id);
    }
}
